from django.contrib.auth.backends import ModelBackend
import re
from .models import User

def get_user_by_account(account):
    '''根据caaount查询用户'''
    try:
        if re.match('^1[345789]\d{9}$', account):
            #手机号登陆
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except Exception:
        return None
    else:
        return user

class UsernameMobileAuthBackend(ModelBackend):
    '''自定义用户认证后端'''

    def authenticate(self, request, username=None, password=None, **kwars):
        '''重写认证方法，实现多账号登陆'''
        #根据传入的username 获取user对象。username可以是手机号或则账号
        user = get_user_by_account(username)
        #校验uer是否存在并校验密码是否正确
        if user and user.check_password(password):
            return user